package models

import (
	"encoding/json"
	"fmt"
	"net/url"
	"strconv"
	"strings"
	"time"

	"github.com/beego/beego/v2/client/httplib"
)

type Asset struct {
	Nickname string
	Bean     struct {
		Total       int
		TodayIn     int
		TodayOut    int
		YestodayIn  int
		YestodayOut int
		MonthIn     int
		MonthOut    int
		ToExpire    []int
	}
	RedPacket struct {
		Total      float64
		ToExpire   float64
		ToExpireJd float64
		ToExpireJx float64
		ToExpireJs float64
	}
}

var Int = func(s string) int {
	i, _ := strconv.Atoi(s)
	return i
}

func DailyAssetsPush() {
	for _, ck := range GetJdCookies() {
		msg := ck.Query()
		if ck.QQ != 0 && Config.QQID != 0 && SendQQ != nil {
			SendQQ(int64(ck.QQ), msg)
		}
		if ck.PushPlus != "" {
			pushPlus(ck.PushPlus, msg)
		}
	}
}

func (ck *JdCookie) Query() string {
	msgs := []string{}
	asset := Asset{}
	if CookieOK(ck) {
		today := time.Now().Local().Format("2006-01-02")
		yestoday := time.Now().Local().Add(-time.Hour * 24).Format("2006-01-02")
		month := time.Now().Local().Format("2006-01")
		page := 1
		end := false
		for {
			if end {
				break
			}
			bds := getJingBeanBalanceDetail(page, fmt.Sprintf("pt_key=%s;pt_pin=%s;", ck.PtKey, ck.PtPin))
			if bds == nil {
				end = true
				break
			}
			for _, bd := range bds {
				amount := Int(bd.Amount)
				if !strings.Contains(bd.Date, month) {
					end = true
					break
				}
				if amount > 0 {
					asset.Bean.MonthIn += amount
				} else {
					asset.Bean.MonthOut += -amount
				}
				if strings.Contains(bd.Date, today) {
					if amount > 0 {
						asset.Bean.TodayIn += amount
					} else {
						asset.Bean.TodayOut += -amount
					}
				}
				if strings.Contains(bd.Date, yestoday) {
					if amount > 0 {
						asset.Bean.YestodayIn += amount
					} else {
						asset.Bean.YestodayOut += -amount
					}
				}
			}
			page++
		}
		msgs = append(msgs, []string{
			fmt.Sprintf("当月收入：%d京豆", asset.Bean.MonthIn),
			fmt.Sprintf("当月支出：%d京豆", asset.Bean.MonthOut),
			fmt.Sprintf("昨日收入：%d京豆", asset.Bean.YestodayIn),
			fmt.Sprintf("昨日支出：%d京豆", asset.Bean.YestodayOut),
			fmt.Sprintf("今日收入：%d京豆", asset.Bean.TodayIn),
			fmt.Sprintf("今日支出：%d京豆", asset.Bean.TodayOut),
		}...)
	} else {
		msgs = append(msgs, []string{
			"提醒：该账号已过期，请重新登录",
		}...)
	}
	ck.PtPin, _ = url.QueryUnescape(ck.PtPin)
	return strings.Join(append([]string{
		fmt.Sprintf("账号：%s", ck.PtPin),
		fmt.Sprintf("昵称：%s", ck.Nickname),
		fmt.Sprintf("备注：%s", ck.Note),
	}, append(msgs, fmt.Sprintf("当前京豆：%v京豆", ck.BeanNum))...), "\n")
}

type BeanDetail struct {
	Date         string `json:"date"`
	Amount       string `json:"amount"`
	EventMassage string `json:"eventMassage"`
}

func getJingBeanBalanceDetail(page int, cookie string) []BeanDetail {
	type AutoGenerated struct {
		Code       string       `json:"code"`
		DetailList []BeanDetail `json:"detailList"`
	}
	a := AutoGenerated{}
	req := httplib.Post(`https://api.m.jd.com/client.action?functionId=getJingBeanBalanceDetail`)
	req.Header("User-Agent", ua)
	req.Header("Host", "api.m.jd.com")
	req.Header("Content-Type", "application/x-www-form-urlencoded")
	req.Header("Cookie", cookie)
	req.Body(fmt.Sprintf(`body={"pageSize": "20", "page": "%d"}&appid=ld`, page))
	data, err := req.Bytes()
	if err != nil {
		return nil
	}
	json.Unmarshal(data, &a)
	return a.DetailList
}
